<?php
/**
 *
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);

namespace app\common\service;

use app\admin\controller\SettingController;
use app\common\model\SettingGroup;
use app\admin\model\AdminMenu;
use app\common\model\Setting;
use think\facade\Cache;

class SettingService
{

    /**
     * 设置缓存
     * @param SettingGroup $data
     * @return bool
     */
    public function createCache(SettingGroup $data): bool
    {

        $cache_key = $this->getSettingCacheKey($data->code);

        $cache_value = [];

        foreach ($data->setting as $setting) {
            $key_setting = [];
            foreach ($setting->content as $content) {
                $key_setting[$content['field']] = $content['content'];
            }
            $cache_value[$setting->code] = $key_setting;
        }


        return Cache::set($cache_key, $cache_value);
    }

    public function getSettingCacheKey($code): string
    {
        return 'setting:' . $code;
    }

    /**
     * 获取设置内容
     * @param string|array $name
     */
    public function getSetting($name)
    {
        if(empty($name)){
            return [];
        }

        // 从缓存中取，提高性能
        if ( strpos($name, '.') === false) {
            $cache_key = $this->getSettingCacheKey($name);
            if (Cache::has($cache_key)) {
                return Cache::get($cache_key);
            }
            // 缓存没有就从数据库取
            return $this->getDatabaseSetting($name);
        }

        $arr       = explode('.', $name);
        $cache_key = $this->getSettingCacheKey($arr[0]);
        if (Cache::has($cache_key)) {
            $cache = Cache::get($cache_key);
            return isset($arr[2]) ? ($cache[$arr[1]][$arr[2]] ?? null) : ($cache[$arr[1]] ?? null);
        }

        // 缓存没有就从数据库取
        return $this->getDatabaseSetting($name);
    }

    /**
     * 获取数据库配置
     * @param $name
     * @return array|mixed|null
     */
    public function getDatabaseSetting($name)
    {
        $model = new SettingGroup;
        if (empty($name) || strpos($name, '.') === false) {
            $result = [];
            $group  = $model->where('code', $name)->findOrEmpty();
            if (!$group->isEmpty()) {
                $result = [];
                foreach ($group->setting as $setting) {
                    $key_setting = [];
                    foreach ($setting->content as $content) {
                        $key_setting[$content['field']] = $content['content'];
                    }
                    $result[$setting->code] = $key_setting;
                }
            }

            return $result;
        }

        $arr   = explode('.', $name);
        $count = count($arr);

        $setting = Setting::where('code', '=', $arr[1])->findOrEmpty();

        if (!$setting->isEmpty()) {

            if ($count === 2) {
                $result = [];
                foreach ($setting->content as $content) {
                    $result[$content['field']] = $content['content'];
                }

                return $result;
            }

            foreach ($setting->content as $content) {
                if ($content['field'] === $arr[2]) {
                    return $content['content'];
                }
            }
        }

        return null;
    }


    /**
     * 生成配置文件
     * @param SettingGroup $data
     * @return bool
     */
    public function createSettingMenu(SettingGroup $data): bool
    {
        $function = <<<EOF
    /**
    * [GROUP_NAME]
    * @return string
    * @throws Exception
    */
    public function [GROUP_CODE]()
    {
        return \$this->show([GROUP_ID]);
    }\n
}//append_menu
EOF;

        $url  = $this->getSettingMenuUrl($data);
        $menu = (new AdminMenu)->where('url', $url)->findOrEmpty();
        if ($menu->isEmpty()) {
            $result = AdminMenu::create([
                'parent_id' => 43,
                'name'      => $data->name,
                'icon'      => $data->icon,
                'is_show'   => 1,
                'url'       => $url
            ]);
        } else {
            $menu->name = $data->name;
            $menu->icon = $data->icon;
            $menu->url  = $url;
            $result     = $menu->save();
        }

        if (!method_exists(SettingController::class, $data->code)) {

            $function = str_replace(array('[GROUP_CODE]', '[GROUP_ID]', '[GROUP_NAME]'), array($data->code, $data->id, $data->name), $function);

            $file_path = app_path() . '/admin/controller/SettingController.php';
            $file      = file_get_contents($file_path);
            $file      = str_replace('}//append_menu', $function, $file);
            file_put_contents($file_path, $file);
        }

        return (bool)$result;
    }

    /**
     * 获取菜单url
     * @param $data
     * @return string
     */
    public function getSettingMenuUrl($data): string
    {
        return 'admin/setting/' . $data->code;
    }
}